class Mind::PagesController < Mind::MindController
  upload_status_for :upload

  def upload_status
   render :inline => "<%= upload_progress.completed_percent rescue 0 %> % ", :layout => false
  end

  def upload
    @message = 'Error'
    if request.post?
      allowed = app_config[:vision_file_size].to_i.kilobytes
      size = params[:vision][:uploaded_data].size
      if size < allowed
        @message = h.number_to_human_size(size)
        @vision = Vision.new(params[:vision])
        @vision.friend = current_friend
        @vision.public = true
        @vision.save
      else
        @message = _("overflow", h.number_to_human_size(size), h.number_to_human_size(allowed))  
      end
    end
    finish_upload_status "'#{@message}'"
  end


  def dropvision
    @vision = Vision.find(params[:id].split('_').first)    
    img = @vision.public_filename :display
    bigimg = @vision.public_filename
    return nil unless img
    url = ""
    #url << request.relative_url_root.to_s << "/"
    #url << @vision.image_options[:base_url] << "/"    
    @content = "<div id='vision-#{@vision.id.to_s}' style='text-align:center;'>\n\n"
    @content << "<a href='#{url+bigimg}'>\n<img src='#{url+img}' alt='#{@vision.name}'/>\n</a>"
    @content << "\n\n<br/>\n\n</div>"              
  end

  def destroy
    if request.post? 
      @page = Page.find(params[:id])
      if (@page.friend.id==current_friend.id) or (current_friend.in_domain? :admin)
       @page.destroy
      end
       redirect_to pags_url
    else
      redirect_to :action => 'edit', :id => params[:id]
    end
  end

  # edit page
  # admin can edit all public pages, but has none for him self
  def edit
    @current_page = params[:current_page] || 1    
    @page = (current_friend.in_domain? :admin)? Page.find(params[:id])  : Page.find(params[:id], :conditions => "friend_id = #{current_friend.id}")
    if not @page.nil? and request.post?
        @page.header = params[:page][:header]
        @page.content = params[:page][:content]
        @page.public = (not params[:page][:public].nil? and params[:page][:public]=='on')
        if @page.save     
          redirect_to p_url(:page => @current_page)
        end     
    end
  end

  def new
    if request.post?
      @page = Page.new(params[:page])
      @page.friend = current_friend
      @page.public = (not params[:page][:public].nil? and params[:page][:public]=='on')
      if @page.save
        redirect_to pags_url
      end
    else
      @page = Page.new
      @current_page = 'new'
     # @page.header = Time.now.strftime("%d.%m.%Y")
    end
  end

end